jQuery('document').ready(function(){
	$('body').append('<div id="divOptionSelect" class="modal hide fade" tabindex="-1" role="dialog" style="position:absolute; width:898px; height:493px; left:50%; margin-left:-449px; top:50%; margin-top:-247px;" ><!-- 2013-12-03 aria 관련 속성 삭제 (w3c validation) -->'
			+ '	<!-- [D] 팝업사이즈 : width:898px; -->'
			+ '	<section class="popup" style="width:898px;"  >'
			+ '		<div class="title">'
			+ '			<h1>' + $('#_system_name').val() + ' 장비/조회 값 선택</h1>'
			+ '			<p class="pop_close"><a href="#" onClick="$(\'#divOptionSelect\').modal(\'hide\')"><img src="/images/common/btn_popup_close.png" alt="닫기" /></a></p>'
			+ '		</div>'
			+ '		<div class="popContainer">'
			+ '			<p class="txt">' + $('#_system_name').val() + '의 장비 구분 &gt; 장비 &gt; 조회값을 순차적으로 선택하신 후 ‘확인’ 버튼을 클릭하세요.<br />선택 장비로 여러 조회값(계측포인트, 지표, 가동시간)을 조회 할 수 있습니다.</p>'
			+ '			<div class="popBox clear02">'
			+ '				<!-- 장비 구분 -->'
			+ '				<div class="fl popGroup01">'
			+ '					<p class="groupTitle">장비 구분</p>'
			+ '					<div class="groupArea">'
			+ '						<ul class="listStyle" id="sGrp01">'
			+ '						</ul>'
			+ '					</div>'
			+ '				</div>'
			+ '				<!-- //장비 구분 -->'
			+ '				<!-- 장비 -->'
			+ '				<div class="fl popGroup02">'
			+ '					<p class="groupTitle">장비</p>'
			+ '					<div class="groupArea">'
			+ '						<ul class="listStyle" id="sGrp02"> <!-- id : sGrp02 -->'
			+ '						</ul>'
			+ '					</div>'
			+ '				</div>'
			+ '				<!-- //장비 -->'
			+ '				<div class="fl popGroup03">'
			+ '					<p class="groupTitle">'
			+ '						조회값'
			+ '						<!-- [D] id와 lable for 값이 동일해야 함. -->'
			+ '						<input type="radio" name="choice" id="choice01" class="inputRadio ml10" value="1" checked="checked" /><label for="choice01">분류별</label>'
			+ '						<input type="radio" name="choice" id="choice02" class="inputRadio" value="2" /><label for="choice02">단위별</label>'
			+ '					</p>'
			+ '					<div class="groupArea br clear02">'
			+ '						<!-- '
			+ '						조회값의 텍스트수는 최대 36자리까지 입력 가능'
			+ '						두 칸으로 나뉘어져 있는 선택영역의 표시 룰  : '
			+ '									- 분류별을 선택한 경우 : 좌측에 계측 포인트 목록이 표시되고 나머지 목록은 오른쪽에 표시'
			+ '									- 단위별을 선택한 경우 : 전체의 갯수를 반씩 나누어 표시. 홀수인 경우 왼쪽에 1개 더 많이 표시'
			+ '						-->'
			+ '						<div class="fl group">'
			+ '							<!-- 왼쪽 영역 -->'
			+ '							<div class="divArea mt8">'
			+ '								<ul id="sGrp03" class="listStyle02 sGrp03">'
			+ '								</ul>'
			+ '							</div>'
			+ '						</div>'
			+ '						<!-- 오른쪽 영역 -->'
			+ '						<div class="fl group">'
			+ '							<div class="divArea mt8">'
			+ '								<ul class="listStyle02 sGrp03"><!-- 2013-12-03  중복아이디 삭제 -->'
			+ '								</ul>'
			+ '							</div>'
			+ '						</div>'
			+ '					</div>'
			+ '				</div>'
			+ '				<!-- //조회값 -->'
			+ '			</div>'
			+ '			<!-- 2013-12-03 .fl .itemDel 스타일을 /css/custom/option_select.css 로 이동 -->'
			+ '			<div class="choiceBox">'
			+ '				<ul class="choiceList clear02">'
			+ '				</ul>'
			+ '			</div>'
			+ '			<!-- 버튼 -->'
			+ '			<div class="btn_area02 mt15">'
			+ '				<div class="fl">'
			+ '					<!-- [D] 비활성화시 : 주석처리 해 놓음 -->'
			+ '					<a id="btnInit" class="on" onclick="initChoiceBox($(this))"><span>초기화</span></a>'
			+ '					<!-- [D] 활성화시 : 주석처리 해 놓음 -->'
			+ '					<!-- <a href="#link"><span>초기화</span></a> -->'
			+ '				</div>'
			+ '				<div class="fr">'
			+ '					<a href="#" onClick="findFgFunction.senddata(); $(\'#divOptionSelect\').modal(\'hide\')" class="on"><span>확인</span></a>'
			+ '					<a href="#" onClick="$(\'#divOptionSelect\').modal(\'hide\')" class="on"><span>취소</span></a>'
			+ '				</div>'
			+ '			</div>'
			+ '			<!-- //버튼 -->'
			+ '		</div>'
			+ '	</section>'
			+ '</div>'
			+ '<!-- //모달팝업 내용 -->');
});


//데이터 설정 부분
var data1 = Object.create(bemsSelectList);
var data2 = Object.create(bemsSelectList);
var data3 = Object.create(bemsSelectList);

var findFgFunction = {
		fgopenpopup : function(){
			// 검색창을 띄울 때 아래 함수를 실행시키면 된다. 
			oSelect.openWindow("#divOptionSelect");

			var params = {
				'system_group_id' : $('#_system_group_id').val() 
				, 'system_id' : $('#_system_id').val()
			};
			$.ajax({
	 		    url : "/fa/ajax/selectSystemGroupFacilityGroupList.do",
	 		    type : "POST",
	 		    dataType : "json",
	 		    data : params, 
	 		    success : function(data){
	 				data1.gid = 'sGrp01';
	 				data1.selector = 'sGrp01';
	 				data1.type = '01'; // 01 : 한개만 선택, 02: 여러개 선택
	 				data1.selected = null;
	 				data1.data = [];
	 				data1.handler = 'findFgFunction.fgclick'
	 				data.fglist.forEach(function(fgroup){
	 					data1.data.push({id:fgroup.facility_group_id, title:fgroup.facility_group_name});
	 				});
	 				data1.retrieve('data1');
		
	 		    }
			});
		},
		fgclick : function(gIdx, idx, dName, dataSelIndex){
			data1.selected = idx;
			data1.retrieve(dName);
			$('#_facility_group_id').val(idx);
			
			var params = {
				'system_group_id' : $('#_system_group_id').val() 
				, 'system_id' : $('#_system_id').val()
				, 'facility_group_id' : $('#_facility_group_id').val()
			};
			$.ajax({
	 		    url : "/fa/ajax/selectFacilityList.do",
	 		    type : "POST",
	 		    dataType : "json",
	 		    data : params, 
	 		    success : function(data){
	 				data2.gid = 'sGrp02';
	 				data2.selector = 'sGrp02';
	 				data2.type = '01	';
	 				data2.selected = null;
	 				data2.data = [];
	 				data2.handler = 'findFgFunction.fclick'
	 				data.flist.forEach(function(facility){
	 					data2.data.push({id:facility.facility_id, title:facility.facility_name, selected:false, system_id:facility.system_id});
	 				});
	 				data2.retrieve('data2');
	 		    }
			});
		},
		fclick: function(gIdx, idx, dName, dataSelIndex){
			$( "#choice01").unbind( "click" );
			$( "#choice02").unbind( "click" );
			$( "#choice01").bind('click', function(){
				findFgFunction.fclick(gIdx, idx, dName, dataSelIndex);
			});
			$( "#choice02").bind('click', function(){
				findFgFunction.fclick(gIdx, idx, dName, dataSelIndex);
			});
			
			data2.selected = idx;
			data2.retrieve(dName);
			$('#_facility_id').val(idx);
			$('#_facility_name').val(data2.data[dataSelIndex].title);
			$('#_system_id').val(data2.data[dataSelIndex].system_id);
			
			var params = {
					'system_group_id' : $('#_system_group_id').val() 
					, 'system_id' : $('#_system_id').val()
					, 'facility_id' : $('#_facility_id').val()
					, 'orderby' : $('input[name="choice"]:checked').val()
			};
			$.ajax({
	 		    url : "/fa/ajax/selectFacilityPointPatternList.do",
	 		    type : "POST",
	 		    dataType : "json",
	 		    data : params, 
	 		    success : function(data){
					data3.gid = 'sGrp03';
					data3.selector = 'sGrp03';
					data3.type = '02';
					data3.selected = null;
					data3.handler = 'addItem';
	 				data3.data = [];
	 				data3.handler = 'findFgFunction.ppclick';
	 				var prevSelType = null;
	 				var dataCnt = 0;
	 				data.pplist.forEach(function(pp){
						var selected = findFgFunction.selchk(pp);
	 					if('1' ==  $('input[name="choice"]:checked').val()){
	 		 					
	 						// 분류별
	 						if(prevSelType != pp.type){
	 							if('01' == pp.type){
	 								data3.data.push({id:'01',eq: 0, gubun:'title', selected: false, title: '계측포인트', });
	 								dataCnt++;
	 							}else if('02' == pp.type){
	 								data3.data.push({id:'02',eq: 1, gubun:'title', selected: false, title: '지표', });
	 								dataCnt++;
	 							}
	 							prevSelType = pp.type;
	 						}
								
 							if('01' == pp.type){
								data3.data.push({id:dataCnt, eq: 0, gubun:'item', selected: selected, title:pp.facility_desc, type:pp.type
			 						, ddc_id: pp.ddc_id
			 						, display_unit: pp.display_unit
			 						, facility_desc: pp.facility_desc
			 						, facility_id: pp.facility_id
			 						, point_id: pp.point_id
			 						, unit_desc: pp.unit_desc
			 						, unit_name: pp.unit_name
									, pattern_code_id: pp.pattern_code_id
									, pattern_code_name: pp.pattern_code_name});
								dataCnt++;
 							}else if('02' == pp.type){
								data3.data.push({id:dataCnt, eq: 1, gubun:'item', selected: selected, title:pp.pattern_code_name, type:pp.type
			 						, ddc_id: pp.ddc_id
			 						, display_unit: pp.display_unit
			 						, facility_desc: pp.facility_desc
			 						, facility_id: pp.facility_id
			 						, point_id: pp.point_id
			 						, unit_desc: pp.unit_desc
			 						, unit_name: pp.unit_name
									, pattern_code_id: pp.pattern_code_id
									, pattern_code_name: pp.pattern_code_name});
								dataCnt++;
 							}
	 					}else if('2' ==  $('input[name="choice"]:checked').val()){
	 						// 단위별
	 						var dpeq = 0;
	 						if(dataCnt <= (data.pplist.length / 2)){
	 							dpeq = 0;
	 						} else{
	 							dpeq = 1;
	 						}
	 						
	 						if(prevSelType != pp.display_unit){
 								data3.data.push({id:dataCnt,eq: dpeq, gubun:'title', selected: false, title: pp.display_unit });
 								dataCnt++;
	 							prevSelType = pp.display_unit;
	 						}
	 						
 							if('01' == pp.type){
								data3.data.push({id:dataCnt, eq: dpeq, gubun:'item', selected: selected, title:pp.facility_desc, type:pp.type
			 						, ddc_id: pp.ddc_id
			 						, display_unit: pp.display_unit
			 						, facility_desc: pp.facility_desc
			 						, facility_id: pp.facility_id
			 						, point_id: pp.point_id
			 						, unit_desc: pp.unit_desc
			 						, unit_name: pp.unit_name
									, pattern_code_id: pp.pattern_code_id
									, pattern_code_name: pp.pattern_code_name});
								dataCnt++;
 							}else if('02' == pp.type){
								data3.data.push({id:dataCnt, eq: dpeq, gubun:'item', selected: selected, title:pp.pattern_code_name, type:pp.type
			 						, ddc_id: pp.ddc_id
			 						, display_unit: pp.display_unit
			 						, facility_desc: pp.facility_desc
			 						, facility_id: pp.facility_id
			 						, point_id: pp.point_id
			 						, unit_desc: pp.unit_desc
			 						, unit_name: pp.unit_name
									, pattern_code_id: pp.pattern_code_id
									, pattern_code_name: pp.pattern_code_name});
								dataCnt++;
 							}
	 					}
	 				});
	 				data3.data.push({id:'03',eq: 1, gubun:'title', selected: false, title: 'hr', });
	 				data3.data.push({id:++dataCnt,eq: 1, gubun:'info', selected: findFgFunction.selchk({type:'03'}), title: '가동시간(hr)', type:'03'});
	 				
	 				data3.retrieve('data3');
	 		    }
			});	
		},
		ppclick:function(gIdx, idx, dName, dataSelIndex){
			if(5 <= $('input[name="selpops"]').length){
				return false;
			} 
			data3.data[dataSelIndex].selected = true;
			data3.retrieve('data3');
			var selData = '';
			if('01' == data3.data[dataSelIndex].type){
				selData = '<input type="hidden" name="selpops" value="01|' +data3.data[dataSelIndex].ddc_id + '_' + data3.data[dataSelIndex].point_id + '_' + data3.data[dataSelIndex].facility_id + '_' + (data3.data[dataSelIndex].title).replaceAll(' ', '') + '|' + data3.data[dataSelIndex].title + '" />';
			}else if('02' == data3.data[dataSelIndex].type){
				selData = '<input type="hidden" name="selpops" value="02|' + '0000000000_' + data3.data[dataSelIndex].pattern_code_id + '_' + $('#_facility_id').val() + '_' +  (data3.data[dataSelIndex].pattern_code_name).replaceAll(' ', '') +  '|' + data3.data[dataSelIndex].title + '" />';
			}else if('03' == data3.data[dataSelIndex].type){
				selData = '<input type="hidden" name="selpops" value="03|Y|' + data3.data[dataSelIndex].title + '" />';
			}
			
			jQuery(".choiceList.clear02").append ("<li id='item_"+dataSelIndex+"'><a class='fl itemDel' onclick='removeItem(jQuery(this), "+dataSelIndex+", \""+dName+"\");'><img src='/images/common/btn_popup_close02.gif' alt='닫기' /></a><span class='fl txtStyle'>"+data3.data[dataSelIndex].title+"</span>" + selData+ "</li>");
			var bh = jQuery(".choiceList").height();
			jQuery(".choiceBox").scrollTop(bh);
		},
		selchk : function(pp){
			var selflag = false;
			$('input[name="selpops"]').each(function(i, sp){
				var sparr = sp.value.split('|');
				if('01' == pp.type){
					if((pp.ddc_id + '_' + pp.point_id + '_' + pp.facility_id + '_' + (pp.facility_desc).replaceAll(' ', ''))  == sparr[1]){
						selflag = true;	
					}
				}else if('02' == pp.type){
					if('0000000000_' + pp.pattern_code_id + '_' + $('#_facility_id').val() + '_' +  (pp.pattern_code_name).replaceAll(' ', '')  == sparr[1]){
						selflag = true;	
					}
				}else if('03' == pp.type){
					if(pp.type == sparr[0]){
						selflag = true;
					}
				}
			})
			return selflag;
		}, senddata:function(){
			var pointData = '';
			var indexData = '';
			var opTime = '';
			var chkName = '';
			var chkCnt = 0;
			var srchHtml = '';
			$('input[name="selpops"]').each(function(i, sp){
				var sparr = sp.value.split('|');
				if('01' == sparr[0]){
					if('' != pointData){
						pointData += ',';
					}
					if('' != chkName){
						chkName += ',';
					}
					chkName += sparr[2];
					pointData += sparr[1];
					chkCnt++;
					srchHtml += '<li onClick="findFgFunction.removeData(\'01\', \'' + sparr[2] + '\', \'' + sparr[1] +'\', this)"><a href="javascript:void(0);" class="fl"><img src="/images/common/btn_popup_close02.gif" alt="닫기" /></a><span class="fl txtStyle">' + sparr[2] +'</span></li>'
				}
			});
			$('input[name="selpops"]').each(function(i, sp){
				var sparr = sp.value.split('|');
				if('02' == sparr[0]){
					if('' != indexData){
						indexData += ',';
					}
					if('' != chkName){
						chkName += ',';
					}
					chkName += sparr[2];
					indexData += sparr[1];
					chkCnt++;
					srchHtml += '<li onClick="findFgFunction.removeData(\'02\', \'' + sparr[2] + '\', \'' + sparr[1] +'\', this)"><a href="javascript:void(0);" class="fl"><img src="/images/common/btn_popup_close02.gif" alt="닫기" /></a><span class="fl txtStyle">' + sparr[2] +'</span></li>'
				}
			});
			$('input[name="selpops"]').each(function(i, sp){
				var sparr = sp.value.split('|');
				if('03' == sparr[0]){
					opTime += sparr[1];
					chkCnt++;
					srchHtml += '<li onClick="findFgFunction.removeData(\'03\', \'' + sparr[2] + '\', \'' + sparr[1] +'\', this)"><a href="javascript:void(0);" class="fl"><img src="/images/common/btn_popup_close02.gif" alt="닫기" /></a><span class="fl txtStyle">' + sparr[2] +'</span></li>'
				}
			});
			$('#point').val(pointData);
			$('#index').val(indexData);
			$('#opTime').val(opTime);
			$('#chkName').val(chkName);
			$('#chkCnt').val(chkCnt);
			$('#dppphr > p').html($('#_facility_name').val());
			// 기존 데이터 삭제
			$('#dppphr > ul > li').remove();
			$('#dppphr > ul').append(srchHtml);
			
		},
		removeData:function(type, title, data,obj){
			
			if('01' == type){
				var p = $('#point').val().split(',');
				var rp = '';
				for(var i = 0; i <p.length;i++){
					if(data != p[i]){	
						if('' != rp){
							rp +=',';
						}
						rp+= p[i];
					}	
				}
				$('#point').val(rp);
			}
			if('02' == type){
				var idx = $('#index').val().split(',');
				var ridx = '';
				for(var i = 0; i <idx.length;i++){
					if(data != idx[i]){
						if('' != ridx){
							ridx +=',';
						}
						ridx+= idx[i];
					}	
				}
				$('#index').val(ridx);
			}
			if('03' == type){
				$('#opTime').val('');				
			}
			var t =  $('#chkName').val().split(',');
			var rt = '';
			for(var i = 0; i <t.length;i++){
				if(title != t[i]){
					if('' != rt){
						rt +=',';
					}
					rt+= t[i];
				}
			}
			$('#chkName').val(rt);
			$('#chkCnt').val(($('#chkCnt').val() - 1));
			if(0 == $('#chkCnt').val()){
				$('#_facility_name').val('');
				$('#dppphr > p').html('');
			}
			$(obj).remove();
		}
};